﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TaoNiuOA.Models;

namespace TaoNiuOA.Web.Controllers
{
    public class CheckingStrategyController : Controller
    {
        private DbEntity db = new DbEntity();

        [IsAdmin]
        public ViewResult Index()
        {
            return View(db.CheckingStrategies.ToList());
        }

        [IsAdmin]
        public ActionResult Create()
        {
            ViewBag.ApplyTypeID = new SelectList(db.ApplyTypes, "ApplyTypeID", "TypeName");
            return View();
        }

        [IsAdmin]
        [HttpPost]
        public ActionResult Create(CheckingStrategy checkingstrategy)
        {
            ViewBag.ApplyTypeID = new SelectList(db.ApplyTypes, "ApplyTypeID", "TypeName");
            if (ModelState.IsValid)
            {
                foreach (var item in db.CheckingStrategies)
                {
                    if (item.ApplyTypeID == checkingstrategy.ApplyTypeID)
                    {
                        ModelState.AddModelError("ApplyTypeID", "该类型已经存在");
                        return View(checkingstrategy);
                    }
                }
                db.CheckingStrategies.Add(checkingstrategy);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(checkingstrategy);
        }

        [IsAdmin]
        public ActionResult Edit(int id)
        {
            CheckingStrategy checkingstrategy = db.CheckingStrategies.Find(id);
            return View(checkingstrategy);
        }

        [IsAdmin]
        [HttpPost]
        public ActionResult Edit(CheckingStrategy checkingstrategy)
        {
            if (ModelState.IsValid)
            {
                db.Entry(checkingstrategy).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(checkingstrategy);
        }

        [IsAdmin]
        [HttpPost]
        public ActionResult Delete(int id)
        {
            try
            {
                CheckingStrategy checkingstrategy = db.CheckingStrategies.Find(id);
                db.CheckingStrategies.Remove(checkingstrategy);
                db.SaveChanges();
                return Json("删除成功");
            }
            catch { return Json("删除失败"); }
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}